/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package net.worlds.object;

import java.awt.Color;
import java.awt.Graphics;
import net.worlds.WorldsException;
import net.worlds.Main;
import net.worlds.PropChangeHandler;
import org.jbox2d.common.Vec2D;
import org.jbox2d.dynamics.joints.RevoluteJoint;
import org.jbox2d.dynamics.joints.RevoluteJointDef;


public class Hinge extends Joint{
    public Hinge() throws WorldsException
    {
        super("Hinge");
        addPropChangeHandler("MotorTorque", new PropChangeHandler()
        {

            @Override
            public void handle(Object oldValue, final Object value) throws WorldsException {
                if(inWorld)
                {
                    ((RevoluteJoint)joint).setMaxMotorTorque((Float) value * 10000);
                    wakeupParts();
                }
            }

        });
        addPropChangeHandler("MotorSpeed", new PropChangeHandler()
        {

            @Override
            public void handle(Object oldValue, final Object value) throws WorldsException {
                if(inWorld)
                {
                    ((RevoluteJoint)joint).setMotorSpeed((Float) value);
                    wakeupParts();
                }

            }
        });
        //x_;
    }
    @Override
    protected void createJoint() {
        try {
            if (joint != null && !joint.isDead) {
                return;
            }
            jointDef = new RevoluteJointDef();
            jointDef.body1 = part1.getBody();
            jointDef.body2 = part2.getBody();
            ((RevoluteJointDef) jointDef).initialize(jointDef.body1, jointDef.body2, anchor);
            joint = world.addJoint(jointDef);
            ((RevoluteJoint) joint).setMaxMotorTorque(getFloatProp("MotorTorque") * 10000);
            ((RevoluteJoint) joint).enableMotor(true);
            ((RevoluteJoint)joint).setMotorSpeed(getFloatProp("MotorSpeed"));
            wakeupParts();
        } catch (WorldsException ex) {
            throw new RuntimeException(ex);
        }
    }
    public Vec2D getLocalAnchor1()
    {
        return new Vec2D(joint.getAnchor1());
    }
    @Override
    public void draw(Graphics g) throws WorldsException
    {
        if(disabled || !getBooleanProp("Visible") || part1 == null || part2 == null || part1.disabled || part2.disabled)
            return;
        if(joint == null)
            return;
        Vec2D screenPos = new Vec2D(joint.getAnchor1()).worldToScreen(Main.getView());
        Color c = getColorProp("Color");
        g.setColor(new Color(c.getRed(), c.getGreen(), c.getBlue(), 128));
        g.fillOval((int) screenPos.x - 5, (int) screenPos.y - 5, 10, 10);
        if(selected)
        {
            g.setColor(Color.white);
            g.drawOval((int) screenPos.x - 5, (int) screenPos.y - 5, 10, 10);
        }
    }
}
